/**
 * Statistics Integration Module
 * This module can be imported into the existing server.js to add statistics tracking
 */

import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import StatsTracker from './stats-tracker.js';
import { createStatsMiddleware } from './stats-middleware.js';

// Create stats tracker instance
const statsTracker = new StatsTracker();

// Create stats middleware
const statsMiddleware = createStatsMiddleware(statsTracker);

// Stats API endpoints handler
function setupStatsAPI(app) {
    // Get summary statistics
    app.get('/api/stats/summary', (req, res) => {
        try {
            const summary = statsTracker.getSummaryStats();
            const users = statsTracker.getStats();
            const historical = statsTracker.getHistoricalData(12); // Last hour
            
            res.json({
                summary,
                users,
                historical,
                timestamp: new Date().toISOString()
            });
        } catch (error) {
            console.error('Error fetching summary stats:', error);
            res.status(500).json({ error: 'Failed to fetch statistics' });
        }
    });

    // Get user-specific statistics
    app.get('/api/stats/user/:username', (req, res) => {
        try {
            const { username } = req.params;
            const userStats = statsTracker.getStats(username);
            
            if (!userStats) {
                return res.status(404).json({ error: 'User not found' });
            }
            
            res.json({
                username,
                stats: userStats,
                timestamp: new Date().toISOString()
            });
        } catch (error) {
            console.error('Error fetching user stats:', error);
            res.status(500).json({ error: 'Failed to fetch user statistics' });
        }
    });

    // Get top users by metric
    app.get('/api/stats/top/:metric', (req, res) => {
        try {
            const { metric } = req.params;
            const { limit = 10, interval } = req.query;
            
            const validMetrics = ['requests', 'duration', 'size', 'errors'];
            if (!validMetrics.includes(metric)) {
                return res.status(400).json({ 
                    error: `Invalid metric. Must be one of: ${validMetrics.join(', ')}` 
                });
            }
            
            const topUsers = statsTracker.getTopUsers(metric, parseInt(limit), interval);
            
            res.json({
                metric,
                limit: parseInt(limit),
                interval: interval || 'current',
                users: topUsers,
                timestamp: new Date().toISOString()
            });
        } catch (error) {
            console.error('Error fetching top users:', error);
            res.status(500).json({ error: 'Failed to fetch top users' });
        }
    });

    // Get interval statistics
    app.get('/api/stats/intervals', (req, res) => {
        try {
            const { count = 12 } = req.query;
            const historical = statsTracker.getHistoricalData(parseInt(count));
            
            res.json({
                intervalCount: parseInt(count),
                data: historical,
                timestamp: new Date().toISOString()
            });
        } catch (error) {
            console.error('Error fetching interval stats:', error);
            res.status(500).json({ error: 'Failed to fetch interval statistics' });
        }
    });

    // Serve stats dashboard
    app.get('/stats', (req, res) => {
        const __dirname = dirname(fileURLToPath(import.meta.url));
        res.sendFile(join(dirname(__dirname), 'public', 'stats-dashboard.html'));
    });

    console.log('[Stats] Statistics tracking initialized');
    console.log('[Stats] Dashboard available at: /stats');
}

// Enhanced tracking function that can be called directly
function trackRequest(username, requestData) {
    return statsTracker.trackRequest(username, requestData);
}

// Get stats for external use
function getStats() {
    return statsTracker.getStats();
}

// Export everything needed for integration
export {
    statsMiddleware,
    setupStatsAPI,
    trackRequest,
    getStats,
    statsTracker
};